package com.spzx.order.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.order.domain.*;
import com.spzx.order.domain.dto.OrderInfoDTO;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.ProductSku;
import com.spzx.product.api.domain.SkuPrice;
import com.spzx.product.api.domain.vo.SkuLockVo;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.api.domain.UserAddress;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.service.IOrderInfoService;
import org.springframework.util.CollectionUtils;

/**
 * 订单Service业务层处理
 *
 * @author shr
 * @since 2024-07-31
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {
    @Resource
    private OrderInfoMapper orderInfoMapper;
    @Resource
    private OrderItemMapper orderItemMapper;
    @Resource
    private OrderLogMapper orderLogMapper;
    @Resource
    private RemoteCartService remoteCartService;
    @Resource
    private RemoteProductService remoteProductService;
    @Resource
    private RemoteUserAddressService remoteUserAddressService;
    @Resource
    private RedisTemplate<String, String> stringRedisTemplate;
    @Resource
    private RabbitService rabbitService;

    /**
     * 查询订单列表
     *
     * @param orderInfoDTO 查询条件
     * @return 订单
     */
    @Override
    public List<OrderInfo> selectOrderInfoList(OrderInfoDTO orderInfoDTO) {
        return orderInfoMapper.selectOrderInfoList(orderInfoDTO);
    }

    @Override
    public Long submitOrder(OrderForm orderForm) {

        Long userId = SecurityContextHolder.getUserId();
        //通过判断订单流水号是否存在且和要提交的订单中的流水号相同，判断是否重复提交
        String userTradeKey = "user:order:tradeNo:" + userId;
        String scriptText = """
                if redis.call("get",KEYS[1]) == ARGV[1]
                then
                    return redis.call("del",KEYS[1])
                else
                    return 0
                end""";
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptText(scriptText);
        redisScript.setResultType(Long.class);
        Long flag = stringRedisTemplate.execute(redisScript, List.of(userTradeKey), orderForm.getTradeNo());
        if (flag == 0) {
            throw new ServiceException("请勿重复提交订单，请稍后尝试");
        }

        //校验订单中的价格信息
        List<OrderItem> orderItems = orderForm.getOrderItemList();
        if (CollectionUtils.isEmpty(orderItems)) {
            throw new ServiceException("请求不合法");
        }
        List<Long> skuIds = orderItems.stream().map(OrderItem::getSkuId).toList();
        R<List<SkuPrice>> skuPricesResult = remoteProductService.getSkuPriceList(skuIds, SecurityConstants.INNER);
        if (!R.isSuccess(skuPricesResult)) {
            throw new ServiceException(skuPricesResult.getMsg());
        }
        List<SkuPrice> skuPrices = skuPricesResult.getData();
        Map<Long, BigDecimal> skuIdSalePriceMap = skuPrices
                .stream()
                .collect(Collectors.toMap(SkuPrice::getSkuId,
                        SkuPrice::getSalePrice));
        String priceCheckResult = orderItems.stream()
                .filter(orderItem ->
                        orderItem.getSkuPrice().compareTo(skuIdSalePriceMap.get(orderItem.getSkuId())) != 0)
                .map(OrderItem::getSkuName)
                .collect(Collectors.joining(";"));
        if (!StringUtils.isEmpty(priceCheckResult)) {
            //更新购物车价格
            remoteCartService.updateCartPrice(userId, SecurityConstants.INNER);
            throw new ServiceException(priceCheckResult + "订单价格发生变化，请刷新页面后重新下单");
        }

        //校验库存
        List<SkuLockVo> skuLockVos = orderItems.stream().map(
                orderItem -> SkuLockVo.builder()
                        .skuId(orderItem.getSkuId())
                        .skuNum(orderItem.getSkuNum())
                        .HaveStock(false)
                        .build()
        ).toList();
        R<String> CALResult = remoteProductService.checkAndLock(orderForm.getTradeNo(), skuLockVos, SecurityConstants.INNER);
        if (!R.isSuccess(CALResult)) {
            throw new ServiceException(CALResult.getMsg());
        }
        //  返回值不为空将校验库存返回的错误信息抛出
        if (StringUtils.isNotEmpty(CALResult.getData())) {
            throw new ServiceException(CALResult.getData());
        }


        //下单
        Long orderId = null;
        try {
            orderId = saveOrder(orderForm);
        } catch (Exception e) {
            //下单失败需要解锁库存
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_UNLOCK, orderForm.getTradeNo());
            throw new ServiceException("下单失败");
        }

        //在购物车中删除订单中的选中的商品
        R<Boolean> deleteResult = remoteCartService.deleteCartCheckedList(userId, SecurityConstants.INNER);
        if (!R.isSuccess(deleteResult)) {
            throw new ServiceException(deleteResult.getMsg());
        }

        // 发送延迟消息，15分钟后若未支付则直接取消订单
        rabbitService.sendDelayMessage(
                MqConst.EXCHANGE_CANCEL_ORDER,
                MqConst.ROUTING_CANCEL_ORDER,
                orderId,
                MqConst.CANCEL_ORDER_DELAY_TIME);

        return orderId;
    }

    /**
     * 下单
     * 保存订单和订单明细
     *
     * @param orderForm 订单信息
     * @return orderId
     */
    private Long saveOrder(OrderForm orderForm) {
        Long userId = SecurityContextHolder.getUserId();
        String userName = SecurityContextHolder.getUserName();

        R<UserAddress> userAddressResult = remoteUserAddressService.getUserAddress(orderForm.getUserAddressId(),
                SecurityConstants.INNER);
        if (!R.isSuccess(userAddressResult)) {
            throw new ServiceException(userAddressResult.getMsg());
        }
        UserAddress userAddress = userAddressResult.getData();

        List<OrderItem> orderItems = orderForm.getOrderItemList();
        BigDecimal totalAmount = orderItems
                .stream()
                .map(orderItem -> orderItem.getSkuPrice()
                        .multiply(new BigDecimal(orderItem.getSkuNum())))
                .reduce(new BigDecimal(0), BigDecimal::add);
        //保存订单
        OrderInfo orderInfo = OrderInfo.builder()
                .orderNo(orderForm.getTradeNo())
                .userId(userId)
                .nickName(userName)
                .remark(orderForm.getRemark())
                .orderStatus(0)
                //收件人信息
                .receiverName(userAddress.getName())
                .receiverPhone(userAddress.getPhone())
                .receiverTagName(userAddress.getTagName())
                .receiverProvince(userAddress.getProvinceCode())
                .receiverCity(userAddress.getCityCode())
                .receiverDistrict(userAddress.getDistrictCode())
                .receiverAddress(userAddress.getFullAddress())
                .originalTotalAmount(totalAmount)
                //价格优惠  --- 暂无逻辑
                .couponAmount(new BigDecimal(0))
                //运费
                .freightFee(orderForm.getFreightFee())
                .totalAmount(totalAmount)
                .build();
        orderInfoMapper.insert(orderInfo);

        //保存订单明细
        orderItems.forEach(orderItem -> {
            orderItem.setOrderId(orderInfo.getId());
            orderItemMapper.insert(orderItem);
        });

        //记录日志
        orderLogMapper.insert(OrderLog.builder()
                .orderId(orderInfo.getId())
                //待付款
                .processStatus(0)
                .operateUser(userName)
                .note("提交订单")
                .build());

        return orderInfo.getId();
    }


    @Override
    public OrderInfo selectOrderInfoById(Long id) {
        OrderInfo orderInfo = orderInfoMapper.selectById(id);
        List<OrderItem> orderItems = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>()
                .eq(OrderItem::getOrderId, id));
        orderInfo.setOrderItemList(orderItems);
        return orderInfo;
    }

    @Override
    public TradeVo orderTradeData() {
        Long userId = SecurityContextHolder.getUserId();
        R<List<CartInfo>> cartInfosResult = remoteCartService.getCartCheckedList(userId, SecurityConstants.INNER);
        if (!R.isSuccess(cartInfosResult)) {
            throw new ServiceException(cartInfosResult.getMsg());
        }
        List<CartInfo> cartInfos = cartInfosResult.getData();
        if (CollectionUtils.isEmpty(cartInfos)) {
            throw new ServiceException("购物车中选中商品为空");
        }
        // 封装订单项
        List<OrderItem> orderItems = cartInfos
                .stream()
                .map(cartInfo -> OrderItem.builder()
                        .skuId(cartInfo.getSkuId())
                        .skuName(cartInfo.getSkuName())
                        .skuNum(cartInfo.getSkuNum())
                        .thumbImg(cartInfo.getThumbImg())
                        .skuPrice(cartInfo.getSkuPrice())
                        .build())
                .collect(Collectors.toList());

        return TradeVo.builder()
                // 订单项
                .orderItemList(orderItems)
                // 计算总金额
                .totalAmount(orderItems.stream()
                        .map(orderItem -> orderItem.getSkuPrice()
                                .multiply(new BigDecimal(orderItem.getSkuNum())))
                        .reduce(BigDecimal.ZERO, BigDecimal::add))
                // 生成交易号
                .tradeNo(generatedTradeNo(userId))
                .build();
    }

    @Override
    public TradeVo buy(Long skuId) {

        R<ProductSku> productSkuResult = remoteProductService.getProductSku(skuId, SecurityConstants.INNER);
        if (!R.isSuccess(productSkuResult)) {
            throw new ServiceException(productSkuResult.getMsg());
        }

        ProductSku productSku = productSkuResult.getData();
        OrderItem orderItem = OrderItem.builder()
                .skuId(productSku.getId())
                .skuName(productSku.getSkuName())
                .skuNum(1)
                .thumbImg(productSku.getThumbImg())
                .skuPrice(productSku.getSalePrice())
                .build();
        return TradeVo.builder()
                .orderItemList(Collections.singletonList(orderItem))
                .totalAmount(orderItem.getSkuPrice())
                .tradeNo(generatedTradeNo(SecurityContextHolder.getUserId()))
                .build();

    }

    @Override
    public List<OrderInfo> selectUserOrderInfoList(Integer orderStatus) {

        Long userId = SecurityContextHolder.getUserId();
        List<OrderInfo> orderInfos = orderInfoMapper.selectList(new LambdaQueryWrapper<OrderInfo>()
                .eq(OrderInfo::getUserId, userId)
                .eq(orderStatus != null, OrderInfo::getOrderStatus, orderStatus)
                .orderBy(true, false, OrderInfo::getCreateTime)
        );
        if (CollectionUtils.isEmpty(orderInfos)) {
            return List.of();
        }
        List<Long> orderInfoIds = orderInfos.stream().map(OrderInfo::getId).toList();
        List<OrderItem> orderItems = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().in(OrderItem::getOrderId, orderInfoIds));
        Map<Long, List<OrderItem>> orderInfoItemMap = orderItems.stream().collect(Collectors.groupingBy(OrderItem::getOrderId));
        orderInfos.forEach(orderInfo -> orderInfo.setOrderItemList(orderInfoItemMap.get(orderInfo.getId())));

        return orderInfos;
    }

    @Override
    public void closeOrder(long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        if (orderInfo != null && orderInfo.getOrderStatus() == 0) {
            orderInfo.setOrderStatus(-1);
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("订单超时未支付");
            orderInfoMapper.updateById(orderInfo);

            //记录日志
            orderLogMapper.insert(OrderLog.builder()
                    .orderId(orderInfo.getId())
                    //待付款
                    .processStatus(-1)
                    .note("订单超时未支付")
                    .build());

            // 解锁库存
            rabbitService.sendMessage(
                    MqConst.EXCHANGE_PRODUCT,
                    MqConst.QUEUE_UNLOCK,
                    orderInfo.getOrderNo());
        }
    }

    @Override
    public void cancelOrder(Long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        if (orderInfo != null && orderInfo.getOrderStatus() == 0) {
            orderInfo.setOrderStatus(-1);
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("用户取消订单");
            orderInfoMapper.updateById(orderInfo);

            //记录日志
            orderLogMapper.insert(OrderLog.builder()
                    .orderId(orderInfo.getId())
                    //待付款
                    .processStatus(-1)
                    .note("用户取消订单")
                    .build());
            // 解锁库存
            rabbitService.sendMessage(
                    MqConst.EXCHANGE_PRODUCT,
                    MqConst.QUEUE_UNLOCK,
                    orderInfo.getOrderNo());
        }
    }

    /**
     * 生成交易号，并保存至redis
     *
     * @param userId 用户id
     * @return tradeNo
     */
    private String generatedTradeNo(Long userId) {
        //构建交易号key
        String key = "user:order:tradeNo:" + userId;
        //生成交易号
        String tradeNo = UUID.randomUUID().toString().replace("-", "");
        //在redis中保存交易号
        stringRedisTemplate.opsForValue().set(key, tradeNo);
        return tradeNo;
    }

}
